package com.zhijian.wharf.service.impl;

import com.zhijian.BusinessException;
import com.zhijian.response.enums.ResponseCodeEnum;
import com.zhijian.util.page.Page;
import com.zhijian.wharf.dao.AreaMapper;
import com.zhijian.wharf.entity.po.Area;
import com.zhijian.wharf.entity.vo.request.AreaSearchVo;
import com.zhijian.wharf.entity.vo.response.AreaVo;
import com.zhijian.wharf.service.AreaService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 科室组织业务处理层
 *
 * @author HCG
 * @date 2022-01-01 15:41:01
 * @version: 1.0
 */
@Slf4j
@Service
public class AreaServiceImpl implements AreaService {

    @Autowired
    private AreaMapper mapper;

    @Override
    public Area selectById(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public AreaVo selectVoById(Long id) {
        return mapper.selectVoById(id);
    }

    @Override
    public void deleteById(Long id) {
        mapper.deleteByPrimaryKey(id);
    }

    @Override
    public Long insert(Area officeGroup) {
        if (officeGroup.getParentId() != 0) {
            //父机构
            Area parentArea = this.selectById(officeGroup.getParentId());
            if (Objects.isNull(parentArea)) {
                throw new BusinessException(ResponseCodeEnum.FAILURE.code, "父机构不存在");
            }
            //等级是父机构的等级+1
            officeGroup.setLevel(parentArea.getLevel() + 1);
        } else {
            officeGroup.setLevel(1);
        }
        Date now = new Date();
        officeGroup.setCreateTime(now);
        officeGroup.setUpdateTime(now);
        return mapper.insert(officeGroup) == 1 ? officeGroup.getId() : 0L;
    }

    @Override
    public boolean update(Area officeGroup) {
        Area oldArea = this.selectById(officeGroup.getId());
        if (Objects.isNull(oldArea)) {
            throw new BusinessException(ResponseCodeEnum.FAILURE.code, "此机构不存在或者已被删除");
        }
        Date now = new Date();
        officeGroup.setUpdateTime(now);
        officeGroup.setLevel(oldArea.getLevel());
        return mapper.updateByPrimaryKey(officeGroup) != 0;
    }

    @Override
    public Integer count(AreaSearchVo officeGroupSearchVo) {
        return mapper.count(officeGroupSearchVo);
    }

    @Override
    public List<AreaVo> selectList(AreaSearchVo officeGroupSearchVo) {
        return mapper.selectList(officeGroupSearchVo);
    }

    @Override
    public Page<AreaVo> selectPage(AreaSearchVo officeGroupSearchVo) {
        //先直接查总数
        int count = count(officeGroupSearchVo);
        //分页
        Page<AreaVo> page = new Page<>(true, count, officeGroupSearchVo.getPageNum(), officeGroupSearchVo.getPageSize());
        officeGroupSearchVo.setStartIndex(page.getStartIndex());
        page.setPage(true);
        page.setTotalCount(count);
        List<AreaVo> responseVos = this.selectList(officeGroupSearchVo);
        page.setData(responseVos);
        return page;
    }

    @Override
    public List<AreaVo> renderTreeList() {
        List<AreaVo> officeGroupVos = this.selectList(AreaSearchVo.builder().build());
        Collections.reverse(officeGroupVos);
        return createTree(officeGroupVos, 0L);
    }

    @Override
    public List<AreaVo> selectListByParentId(Long parentId) {
        return this.selectList(AreaSearchVo.builder()
                .parentId(parentId)
                .build());
    }

    @Override
    public List<Long> concatIdsByParentId(List<Long> ids, Long parentId) {
        List<AreaVo> officeGroupVos = this.selectListByParentId(parentId);
        if (officeGroupVos.isEmpty()) {
            return ids;
        }
        for (AreaVo officeGroupVo : officeGroupVos) {
            ids.add(officeGroupVo.getId());
            ids = concatIdsByParentId(ids, officeGroupVo.getId());
        }
        return ids;
    }

    @Override
    public List<Long> concatIdsByParentId(Long parentId) {
        List<Long> ids = new ArrayList<>();
        ids.add(parentId);
        return concatIdsByParentId(ids, parentId);
    }

    @Override
    public AreaVo selectVoByName(String name) {
        return mapper.selectVoByName(name);
    }

    /**
     * 生成树的方法
     */
    private List<AreaVo> createTree(List<AreaVo> list, Long pid) {
        try {
            //根节点
            List<AreaVo> tempList = new ArrayList<>();
            for (AreaVo vo : list) {
                //父节点是0的，为根节点。
                if (Objects.equals(vo.getParentId(), pid)) {
                    tempList.add(vo);
                }
            }
            //为根id设置子childList是递归调用的
            for (AreaVo vo : tempList) {
                /* 获取根节点下的所有子节点 使用getChild方法*/
                List<AreaVo> childList = setChild(vo.getId(), list);
                //给根节点设置子节点
                vo.setChildren(childList);
            }
            // 输出构建好的菜单数据。
            return tempList;
        } catch (Exception e) {
            return new ArrayList<>();
        }
    }

    /**
     * 获取子节点
     *
     * @param id   父节点id
     * @param list 所有节点列表
     * @return 每个根节点下，所有子节点列表
     */
    private List<AreaVo> setChild(Long id, List<AreaVo> list) {
        //子节点
        List<AreaVo> childList = new ArrayList<>();
        for (AreaVo vo : list) {
            // 遍历所有节点，将所有子节点的父id与传过来的根节点的id比较
            //相等说明：为该根节点的子节点。
            if (vo.getParentId().equals(id)) {
                childList.add(vo);
            }
        }
        //递归
        for (AreaVo vo : childList) {
            vo.setChildren(setChild(vo.getId(), list));
        }
        //如果节点下没有子节点，返回一个空List（递归退出）
        if (childList.isEmpty()) {
            return new ArrayList<>();
        }
        return childList;
    }

}